package com.ff.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ff.common.BaseContext;
import com.ff.common.CustemException;
import com.ff.entity.*;
import com.ff.mapper.OrdersMapper;
import com.ff.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Override
    @Transactional
    public void submit(Orders orders) {
        //获得下单用户id
        Long userId = BaseContext.getThreadContext();
        //获得用户购物车中的数据
        QueryWrapper<ShoppingCart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        if (list==null||list.size()==0){
            throw new CustemException("请先添加购物车");
        }
        //往订单表插入一条订单信息
            //获得用户信息
            User user = userService.getById(userId);
            //获得地址信息
            Long ordersAddressBookId = orders.getAddressBookId();
            AddressBook addressBook = addressBookService.getById(ordersAddressBookId);
            if (addressBook==null){
                throw new CustemException("用户地址信息有误，补能下单");
            }


            //订单号
            long orderId = IdWorker.getId();
            AtomicInteger amount=new AtomicInteger(0);
            List<OrderDetail> orderDetailList=new ArrayList<>();
            for (ShoppingCart tmp:list){
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(orderId);
                orderDetail.setNumber(tmp.getNumber());
                orderDetail.setDishFlavor(tmp.getDishFlavor());
                orderDetail.setDishId(tmp.getDishId());
                orderDetail.setSetmealId(tmp.getSetmealId());
                orderDetail.setName(tmp.getName());
                orderDetail.setImage(tmp.getImage());
                orderDetail.setAmount(tmp.getAmount());
                amount.addAndGet(tmp.getAmount().multiply(new BigDecimal(tmp.getNumber())).intValue());
                orderDetailList.add(orderDetail);
            }
            //设置订单数据
            orders.setId(orderId);
            orders.setOrderTime(LocalDateTime.now());
            orders.setCheckoutTime(LocalDateTime.now());
            orders.setStatus(2);
            orders.setAmount(new BigDecimal(amount.get()));//总金额
            orders.setUserId(userId);
            orders.setNumber(String.valueOf(orderId));
            orders.setUserName(user.getName());
            orders.setConsignee(addressBook.getConsignee());
            orders.setPhone(addressBook.getPhone());
            orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                    + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                    + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                    + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
            //插入数据
            this.save(orders);
        //往订单明细表插入数据或多条数据
            orderDetailService.saveBatch(orderDetailList);
        //清空购物车
            shoppingCartService.removeById(orderId);
    }
}
